package com.mimc.framework.interceptors;

import cn.hutool.core.util.StrUtil;
import com.mimc.common.constant.AppConstants;
import com.mimc.common.constant.WebConstants;
import com.mimc.common.exception.ServiceException;
import com.mimc.common.utils.StringUtils;
import com.mimc.core.model.SysAdmin;
import com.mimc.framework.jwt.AdminTokenUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import io.jboot.Jboot;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class AdminJwtInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        String action=invocation.getActionKey();
        //invocation.getController().getRequest().setAttribute(WebConstants.REQUEST_ACTION,action);
        log.info("当前访问路径：{}",action);
        if(action.startsWith("/admin")){
            List<String> strs=new ArrayList<String>(Arrays.asList("/admin/login/**","/admin/index/**","/admin/article/list"));
            if(StringUtils.matches(action,strs)){
                invocation.invoke();
                return;
            }
            String jwtkey = Jboot.configValue("yminfo.jwtkey");


            String token=invocation.getController().getHeader("token");

            //执行认证
            if (StrUtil.isBlank(token)){
                throw new ServiceException("无token，请重新登录！", AppConstants.CODE_401);
            }
            try {
                if(!AdminTokenUtils.verifyToken(token,jwtkey)){
                    throw new ServiceException("token验证失败，请重新登录！", AppConstants.CODE_401);
                }
            }catch (Exception e){
                throw new ServiceException(e.getMessage(), AppConstants.CODE_401);
            }

            Integer userId=AdminTokenUtils.getCurrentUserId();
            if(userId==null){
                throw new ServiceException("token验证失败，请重新登录！", AppConstants.CODE_401);
            }
            SysAdmin admin=AdminTokenUtils.getCurrentUser();
            if(admin==null){
                throw new ServiceException("用户不存在，请重新登录！", AppConstants.CODE_401);
            }
            invocation.getController().getRequest().setAttribute(WebConstants.REQUEST_ADMIN,admin);

            invocation.invoke();

        }else{
            invocation.invoke();
        }
    }
}
